package com.zhuliyou.ai.controller;


import com.zhuliyou.ai.config.CustomConfig;
import com.zhuliyou.ai.service.FaceMerge;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * 主控制器
 *
 * @author zhuliyou
 * @date 2021/06/02
 */
@RestController
public class MainController {


    @Autowired
    private FaceMerge faceMerge;


    @Autowired
    private CustomConfig customConfig;

    @SneakyThrows
    @PostMapping("faceMerge")
    public void faceMerge(MultipartFile file1, MultipartFile file2, HttpServletResponse response){
        String fileName = file1.getOriginalFilename();
        String fileName2 = file2.getOriginalFilename();
        String prefix = Objects.requireNonNull(fileName).substring(fileName.lastIndexOf("."));
        String prefix2 = Objects.requireNonNull(fileName2).substring(fileName2.lastIndexOf("."));
        List<String> imgType = customConfig.getImgType();
        if (!imgType.contains(prefix) || !imgType.contains(prefix2)) {
            throw new Exception("图片格式不正确!");
        }
        final File basedOnImage = File.createTempFile(UUID.randomUUID().toString().replaceAll("-", ""), prefix);
        final File basedOnImage2 = File.createTempFile(UUID.randomUUID().toString().replaceAll("-", ""), prefix2);
        try {
            file1.transferTo(basedOnImage);
            file2.transferTo(basedOnImage2);
            String base64 = faceMerge.faceMerge(basedOnImage, basedOnImage2);
            ServletOutputStream out = response.getOutputStream();
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = decoder.decodeBuffer(Objects.requireNonNull(base64));
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            out.write(b);
            out.flush();
            out.close();
            System.out.println("换脸成功");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (basedOnImage.exists()) {
                boolean delete = basedOnImage.delete();
            }
            if (basedOnImage2.exists()) {
                boolean delete = basedOnImage2.delete();
            }
        }
    }
}
